package yns.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpHelper {
	
	public HttpHelper(){
		
	}
	
	
	public HttpResponse execute(HttpRequest httpRequest,HttpResponse httpResponse) throws IOException  	{
		
		String sendURL = httpRequest.getSendURL();
		
		if ("".equals(sendURL) || sendURL == null) {
			throw new IOException("URL is null");
		}
		
		String requestMethod = httpRequest.getRequestMethod();
		Map<String, String> requestProperty = httpRequest.getRequestProperty();
		String param = httpRequest.getParam();
		
		
		URL url = new URL(sendURL);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(httpRequest.getProxy());
		
		httpURLConnection.setDoOutput(httpRequest.isDoInput());
		httpURLConnection.setDoInput(httpRequest.isDoInput());
		httpURLConnection.setUseCaches(httpRequest.isUseCaches());

		httpURLConnection.setConnectTimeout(httpRequest.getConnectTimeout());
		httpURLConnection.setReadTimeout(httpRequest.getReadTimeout());
		httpURLConnection.setInstanceFollowRedirects(httpRequest.isInstanceFollowRedirects());

		httpURLConnection.setRequestMethod(requestMethod);

		boolean isHTTPS = sendURL.startsWith("https://");
		boolean hasUserAgent = false;
		if (requestProperty != null) {
			for (Entry<String, String> entry : requestProperty.entrySet()) {
				httpURLConnection.setRequestProperty(entry.getKey(),entry.getValue());
				if (isHTTPS && HttpProperty.UserAgent.equalsIgnoreCase(entry.getKey())) {
					hasUserAgent = true;
				}
			}
		}
		
		
		if (isHTTPS && !hasUserAgent) {
			httpURLConnection.setRequestProperty(HttpProperty.UserAgent, HttpProperty.Chrome46);
		}
		

		if (requestMethod.equals(HttpProperty.POST) && param != null) {
			DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
			out.write(param.getBytes(HttpProperty.UTF8));
			out.flush();
			out.close();
		}
		
		httpURLConnection.connect();
		
		InputStream respStream = httpURLConnection.getInputStream();
		
		
	    int responseCode = httpURLConnection.getResponseCode();
	    Map<String, List<String>> responseHeader = httpURLConnection.getHeaderFields();
		
		httpResponse.setResponseCode(responseCode);
		httpResponse.setResponseHeader(responseHeader);


		if (respStream != null) {
			StringBuilder result = new StringBuilder();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(respStream, httpResponse.getResponseCharset()));

			String lines;
			while ((lines = bufferedReader.readLine()) != null) {
				result.append(lines);
			}

			bufferedReader.close();
			httpURLConnection.disconnect();
			
			httpResponse.setResponseResult(result.toString());
			return httpResponse;
		}

		httpURLConnection.disconnect();

		return null;
	}

}
